
package cookinmaddy.database;

/**
 * ...
 * @author Yog
 */

import cookinmaddy.database.spod.DBUnit; 
import cookinmaddy.database.spod.DBIngredient; 
import cookinmaddy.database.spod.DBVersion;
import cookinmaddy.database.spod.DBRecipe;
import cookinmaddy.database.spod.DBRecipeIngredient;
import php.Exception;
import php.Lib;
  
class DBManager
{	
	private static var _dbMgr : DBManager;
	private var _databaseFile : String;
	private var _conn : Dynamic;
	
	public static function initializeDB(databaseFile : String)
	{
		_dbMgr = new DBManager(databaseFile);
		_dbMgr.open();
	}

	public static function createDB(databaseFile : String)
	{
		_dbMgr = new DBManager(databaseFile);
		_dbMgr.create();
	}	
	
	private function new(databaseFile : String)
	{
		
		_databaseFile = php.Sys.getCwd() + databaseFile ;
	}
	
	private function open()
	{
		if (_conn == null)
		{
			_conn = php.db.Sqlite.open(_databaseFile);		

			php.db.Manager.cnx = _conn;
			php.db.Manager.initialize();		
		}			
	}
	
	private function create()
	{
		try
		{
			var version :Int = DBVersion.CURRENTVERSION;
			trace("init DB & SPOD Manager: " + _databaseFile);
			_conn = php.db.Sqlite.open(_databaseFile);		

			/*try
			{
				if (DBVersion.manager.count() != 1)
				{
					var ver : DBVersion = DBVersion.manager.get(0);
					version = ver.ver;
				}
			}
			catch (exception : String)
			{}*/
			
			var arr = 
			[
	/*			DBUser.DROP_REQUEST,
				DBUser.CREATION_REQUEST_V1,*/
				DBRecipe.DROP_REQUEST,
				DBRecipe.CREATION_REQUEST_V1,
				DBIngredient.DROP_REQUEST,
				DBIngredient.CREATION_REQUEST_V1,		
				DBUnit.DROP_REQUEST,
				DBUnit.CREATION_REQUEST_V1,
				DBUnit.INITIALIZATION_REQUEST_V1,
				DBRecipeIngredient.DROP_REQUEST,
				DBRecipeIngredient.CREATION_REQUEST_V1,	
				DBVersion.DROP_REQUEST,
				DBVersion.CREATION_REQUEST_V1,
				DBVersion.INITIALIZATION_REQUEST_V1
			];

			trace(arr);
			var err = requests(arr);
			if (err.length > 0)
			{
				var ret = "Error(s) encountered while creating database structure <br>";
				for(error in err)
				{
					trace(error);
				}
			}
			
			php.db.Manager.cnx = _conn;
			php.db.Manager.initialize();		
		}
		catch (e : String)
		{
			trace("ERROR " + e);
		}
	}
	
	private function requests(arr : Array<String>) : Array<String>
	{
		if (arr == null || arr.length == 0)
			return [ "No request" ];
		var err : Array<String> = new Array<String>();
		for(request in arr)
		{
			try
			{
				_conn.request(request);
			}
			catch(ex : String)
			{
				err.push(request + " failed with error: (" + ex + ")");
				trace("error");
			}
		}
		return err;
	}
	
	private function close()
	{
		if(_conn != null)
			_conn.close();
	}
}